
#include "VisaSerial.h"
# include <iostream> 
#include<string>

ResourceManager::ResourceManager() : ses(0)
{
//	std::cout << "In ResourceManager CTOR" << std::endl;
	ViStatus status = viOpenDefaultRM (&ses);
	if (status < VI_SUCCESS)
		throw VISAException();
}

ResourceManager::~ResourceManager()
{
//	std::cout << "In ResourceManager Destructor" << std::endl;
	ViStatus status = viClose (ses);
	if (status < VI_SUCCESS)
		throw VISAException();  // should never happen!!
}

Instrument::Instrument(const char* instrumentName) : rm() , instrum(0)
{
//	std::cout << "In Instrument CTOR" << std::endl;
	ViStatus status = viOpen (rm.getSession(), (ViChar *) instrumentName, VI_NULL, VI_NULL, &instrum);
	if (status < VI_SUCCESS)
		throw VISAException();
}

Instrument::~Instrument()
{
//	std::cout << "In Instrument Destructor" << std::endl;
	ViStatus status = viClose (instrum);
	if (status < VI_SUCCESS)
		throw VISAException();  // should never happen!!
}

void Instrument::setAttribute(long attributeConstant, int value)
{
	ViStatus status = viSetAttribute (instrum, attributeConstant, value);
	if (status < VI_SUCCESS)
		throw VISAException();
}

ViUInt32 Instrument::write(char * msg)
{
	ViUInt32 writeCount = 0;
	ViStatus status = viWrite (instrum, (ViBuf) msg, strlen(msg), &writeCount); 
	if (status < VI_SUCCESS)
		throw VISAException();
	return writeCount;
}

std::string Instrument::read(int numToRead, bool timeoutIsError)
{
	unsigned char buffer[100];	// needs to be unsigned to convert to viByte* in viRead
	ViUInt32 retCount =0 ;
	ViStatus status = viRead (instrum, buffer, numToRead, &retCount);
	if (status < VI_SUCCESS)
		if (timeoutIsError || (status != VI_ERROR_TMO))
			throw VISAException();
	buffer[retCount] = '\0';
	return std::string((char *) buffer);
}






